use dotenv::dotenv;
use serde::{Deserialize, Serialize};
use mongodb::{
    bson::{ doc, Document } ,
    options::{ ClientOptions, FindOptions },
    Client,
    Database,
    Collection,
    Cursor
};

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct User {
    pub username: String,
    pub password: String, // 存储哈希后的密码
}

pub async fn get_mongodb_client(mongodb_url : String) -> Result<Client, String> {
    dotenv().ok(); // 加载 .env 文件
    let url = mongodb_url;
    let mut client_options = ClientOptions::parse(&url)
    .await
    .map_err(|e| format!("❌Failed to parse MongoDB URI: {}", e))?;
    client_options.max_pool_size = Some(200);
    client_options.min_pool_size = Some(10);
    // client_options.connect_timeout =  Some(Duration::seconds(5).to_std().unwrap());
    // 连接池设置和连接时间设置
    println!("Loaded MongoDB URI: {}", &url);
    Client::with_options(client_options).map_err(|e| format!("❌Failed to connect to MongoDB: {}", e))
}

pub async fn get_tauriapp_database(client: Client)
->Result<Database, String>{
    let db = client.database("tauri_app");
    return Ok(db);
}

pub async fn get_users_collection(database: Database)
->Result<Collection<User>, String> {
    let users_collection = database.collection::<User>("users");
    return Ok(users_collection);
}
pub async fn get_paths_collection(database: Database)
-> Result<Collection<Document>, String>{
    let users_collection = database.collection::<Document>("cloud_files_path");
    return Ok(users_collection);
}
pub async fn get_oss_collection(database: Database)
-> Result<Collection<Document>, String>{
    let users_collection = database.collection::<Document>("oss_accesskey");
    return Ok(users_collection);
}

pub async fn from_client_get_users_collection(mongodb_url : String)
->Result<Collection<User>, String>{
    let client = get_mongodb_client(mongodb_url).await?;
    let database = get_tauriapp_database(client).await?;
    let collection = get_users_collection(database).await?;
    return Ok(collection);
}

pub async fn from_client_get_paths_collection(mongodb_url : String)
->Result<Collection<Document>, String>{
    let client = get_mongodb_client(mongodb_url).await?;
    let database = get_tauriapp_database(client).await?;
    let collection = get_paths_collection(database).await?;
    return Ok(collection);
}
pub async fn from_client_get_oss_collection(mongodb_url : String)
->Result<Collection<Document>, String>{
    let client = get_mongodb_client(mongodb_url).await?;
    let database = get_tauriapp_database(client).await?;
    let collection = get_oss_collection(database).await?;
    return Ok(collection);
}
pub async fn get_userdoc( user : User, mongdb_url: String)
-> Result<Cursor<Document>, String>{
    let username = user.username;
    let url = mongdb_url.clone();
    let users_collection =
    from_client_get_paths_collection(url).await?;
    let filter = doc! { "username": &username };
    // 使用投影仅获取必要字段
    let options = FindOptions::builder()
        .projection(doc! { 
            "_id": 0,
            "path": 1,
            "timestamp": 1 
        })
        .build();
    let user_doc = users_collection.find(filter)
        .with_options(options)
        .await
        .map_err(|e| format!("查询失败: {}", e))?;
    return Ok(user_doc);
}



// async fn get_username(app_state: &tauri::State<'_, AppState>)
// -> Result<String, String>{
//     let username = {
//         let state = app_state.0.lock().await;
//         state.current_user.clone().ok_or("❌User not logged in")?
//     };
//     return Ok(username);
// }

// async fn from_appstate_get_userdoc(
//     // app_state: tauri::State<'_, AppState>,
//      user : User,
//      mongdb_url: String
// )
// -> Result<Cursor<Document>, String> {
//     // 获取当前登录用户名
//     // let username = get_username(&app_state).await?;
//     // println!("Current user: {}", username);
//     // 查询用户文档
//     let user_doc = get_userdoc(user).await?;
//     Ok(user_doc)
// }